#!/bin/bash

AAF_INSTALLER_VERSION=1.13
AAF_PACKMAN_SOURCE=""
MY_ALIEN_VER="v2-19"

# if [ `hostname -d` == "cern.ch" ]; then 
#	AAF_PACKMAN_SOURCE="-name ALICE::CERN::aliendb7"
# fi

# Sourcing functions library for coloured diagnostic messages
[ -f /etc/init.d/functions ] && . /etc/init.d/functions

# Variable which should contain warning or error message after checking xrootd installation
xrootd_check_message=""

function SetVariables() {

  if [ "x$AAF_CF_DIR" == "x" ]; then
    export AAF_CF_DIR=""
  else
    AAF_CF_DIR="$AAF_CF_DIR/"
  fi

  echo "We are using ${AAF_CF_DIR}aaf.cf ..."

  if [ -e ${AAF_CF_DIR}aaf.cf ]; then
    source ${AAF_CF_DIR}aaf.cf
  else
    echo "${AAF_CF_DIR}aaf.cf was not found !!! You may define \$AAF_CF_DIR variable to directory where your 'aaf.cf' is ..."
    exit 1
  fi

  CheckVariables

#   echo "We are using ${AAF_CF_DIR}aaf.cf ..."
}
function updateAAFInstaller() {
  echo "Upgrade aaf-installer !!!!"
  echo "  rm -f $1"
  echo "  wget -O $1 http://aaf.cern.ch/config/aaf-installer"
  echo "  chmod +x $1"
}
function checkAAFInstallerVersion() {
# This function checks whether the version of AAF installer is the latest or not. It compares AAF_INSTALLER_VERSION from
# current file with that of the file published at http://aaf.cern.ch/config/aaf-installer. If the later is greater
# it suggests updating the script.
 
  message="\nYou need to upgrade your aaf-installer to latest version before proceeding.\nPlease download it from http://aaf.cern.ch/config/aaf-installer \nand replace the existing one - $PWD/aaf-installer\n\n so you do:\n   rm $PWD/aaf-installer\n   wget http://aaf.cern.ch/config/aaf-installer\n   chmod +x aaf-installer\n\n"
  existing_version=$AAF_INSTALLER_VERSION
  latest_version=`wget -q -O - http://aaf.cern.ch/config/aaf-installer`

  latest_version=`echo $latest_version | sed -r -e 's/.*AAF_INSTALLER_VERSION\s*=\s*([[:digit:]]+.[[:digit:]]+).*/\1/'`
  ex_maj=${existing_version%.*}
  ex_min=${existing_version#*.}
  lat_maj=${latest_version%.*}
  lat_min=${latest_version#*.}

  if [ $ex_maj -lt $lat_maj ]; then
    updateAAFInstaller $1
    exit 0
  elif [ $ex_maj -eq $lat_maj ]; then
    if [ $ex_min -lt $lat_min ]; then
    updateAAFInstaller $1
    exit 0
    fi
  fi
}

function CheckVariables() {

  echo ""
  CheckOneVariable ALICE_PROOF_AAF_DIR
#   CheckOneVariable ALICE_PROOF_AAF_ALIEN_API_DIR
  CheckOneVariable ALICE_PROOF_AAF_PROOF_DIR
  CheckOneVariable ALICE_PROOF_AAF_PROOF_XPROOFD_DIR
  CheckOneVariable ALICE_PROOF_AAF_ALIEN_PACKAGES
  CheckOneVariable ALICE_PROOF_AAF_CERTGLOBUS_DIR
  CheckOneVariable ALICE_PROOF_AAF_USER
  CheckOneVariable ALICE_PROOF_AAF_GROUP
  CheckOneVariable ALICE_PROOF_AAF_XROOTD_REDIRECTOR
  CheckOneVariable ALICE_PROOF_AAF_XROOTD_MONALISA
  CheckOneVariable ALICE_PROOF_AAF_XROOTD_SE_NAME
  CheckOneVariable ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  CheckOneVariable ALICE_PROOF_AAF_XROOTD_XRDNAMESPACE
  CheckOneVariable ALICE_PROOF_AAF_XROOTD_XRDDATA
  CheckOneVariable ALICE_PROOF_AAF_ALIEN_DIR
  CheckOneVariable ALICE_PROOF_AAF_ALIEN_VERSION
  CheckOneVariable ALICE_PROOF_AAF_AAF_ALICESOFT_PACKAGE
  CheckOneVariable ALICE_PROOF_AAF_AAF_ALICESOFT_SHARED_DIR
  CheckOneVariable ALICE_PROOF_AAF_AAF_XROOTD_PACKAGE
  CheckOneVariable ALICE_PROOF_AAF_AAF_PROOF_PACKAGE
  CheckOneVariable ALICE_PROOF_AAF_AAF_ALIROOT_PACKAGE
  CheckOneVariable ALICE_PROOF_AAF_PROOF_MASTER
  CheckOneVariable ALICE_PROOF_AAF_PROOF_XrdSecGSISRVNAME
  CheckOneVariable ALICE_PROOF_AAF_TMP_DIR
  CheckOneVariable ALICE_PROOF_AAF_ALIEN_SHARED_DIR
  CheckOneVariable ALICE_PROOF_AAF_PROOF_ROOT_SHARED_DIR
  CheckOneVariable ALICE_PROOF_AAF_PROOF_XPROOFD_SHARED_DIR
  CheckOneVariable ALICE_PROOF_AAF_PROOF_PROOF_CONF_FILE
  CheckOneVariable ALICE_PROOF_AAF_CUSTOM_GRID_MAP_LOCATION append
  CheckOneVariable ALICE_PROOF_AAF_CUSTOM_PATH append
  CheckOneVariable ALICE_PROOF_AAF_PROOF_PORT append 1093

  CheckOneVariable AAF_PROOF_MEMORY_LIMIT_VIRT_MB append 100000
  CheckOneVariable AAF_PROOF_MEMORY_LIMIT_RES_MB append 100000
  CheckOneVariable AAF_PROOF_IDLE_TIMEOUT_SEC append 60
  CheckOneVariable AAF_PROOF_PROOF_MAX_USER_ONLINE append 10
  CheckOneVariable AAF_AFDSMGR_MAX_TRANSFERS append 10
  CheckOneVariable AAF_AFDSMGR_MAX_CORRUPT_AFTER_FAILS append 10

  CheckOneVariable AAF_AFDSMGR_XRD_PREFIX append
  CheckOneVariable ALICE_PROOF_AAF_PROOF_GROUP_UPDATE append 1
  CheckOneVariable ALICE_PROOF_AAF_DS_OPT append "opt:-Av:As:"
  CheckOneVariable AAF_PROOF_EXTRA_CONF append ""
  
  echo ""

  if [ ! -z $ALICE_PROOF_AAF_CUSTOM_PATH ]; then
    export PATH="$ALICE_PROOF_AAF_CUSTOM_PATH:$PATH"
    echo "NEW PATH is $PATH"
  fi
  CheckProgram cmake
  
}

function CheckOneVariable() {
  echo -n "Checking \$$1" 
  cat ${AAF_CF_DIR}aaf.cf | grep "export $1=" > /dev/null 2>&1
  if [ "$?" == "0" ]; then
    echo " [OK]"
  else
    if [ -z "$2" ]; then
      echo " [FAILED]"
      exit 1
    else
      echo "" >> ${AAF_CF_DIR}aaf.cf
     echo "export $1=\"$3\"" >> ${AAF_CF_DIR}aaf.cf
     echo " [OK]"
    fi
  fi
}

function CheckProgram() {
  which $1 &> /dev/null
  if [ "$?" != "0" ]; then
    echo "cmake was not found !!! Install it first !!!"
    exit
  fi
}

function CheckUser() {
  if [ "`whoami`" == "$ALICE_PROOF_AAF_USER" ];then
    echo "User '$ALICE_PROOF_AAF_USER' is ok"
  else
    echo "User `whoami` is not $ALICE_PROOF_AAF_USER"
    exit 1
  fi
}

function CheckRoot() {
  if [ "`whoami`" == "root" ];then
    echo "User is 'root' and it is OK"
  else
    echo "You can't do that with `whoami` user !!!! Login 'root' user !!!!!"
#     echo "Log in as 'root' user and do --clean !!!!!"
    exit 1
  fi
}


function InstallAAF() {

  rm -Rf $ALICE_PROOF_AAF_TMP_DIR/

  InitAAFLocal

  PrintAafInfo
  
  echo "Copying aaf.cf in $ALICE_PROOF_AAF_DIR ..."

  cp -f aaf.cf $ALICE_PROOF_AAF_DIR/
  chown $ALICE_PROOF_AAF_USER:$ALICE_PROOF_AAF_GROUP $ALICE_PROOF_AAF_DIR/aaf.cf


}

function RecreateAfdsmgrLinks() {
#   rm -f /etc/init.d/afdsmgrd /etc/sysconfig/afdsmgrd
  ln -nfs $ALICE_PROOF_AAF_PROOF_XPROOFD_DIR/afdsmgrd.sysconfig /etc/sysconfig/afdsmgrd
  ln -nfs $ALICE_PROOF_AAF_DIR/root/etc/proof/init.d/afdsmgrd /etc/init.d/afdsmgrd
  echo "Links updated OK."
  
  
}

function InitAAFLocal() {

  mkdir -p $ALICE_PROOF_AAF_DIR 
	
	ClearTmpDirectory

  mkdir -p $ALICE_PROOF_AAF_PROOF_DIR
  mkdir -p $ALICE_PROOF_AAF_DIR/.alien
  mkdir -p $ALICE_PROOF_AAF_DIR/.authz
  mkdir -p $ALICE_PROOF_AAF_DIR/scripts
  wget -O $ALICE_PROOF_AAF_DIR/scripts/aaf.sh http://xrootd-dm.googlecode.com/svn/trunk/etc/PROOF_AAF/scripts/aaf.sh > /dev/null 2>&1
  chmod +x $ALICE_PROOF_AAF_DIR/scripts/aaf.sh
  mkdir -p $ALICE_PROOF_AAF_DIR/logs 
  chown -R $ALICE_PROOF_AAF_USER:$ALICE_PROOF_AAF_GROUP $ALICE_PROOF_AAF_DIR

  DISTRIBUTION_NAME=`cat /etc/*-release | awk '{print $1 $2}'`
  if [ "$DISTRIBUTION_NAME" == "ScientificLinux" ]; then
    echo "SL"
    rm -f /etc/init.d/xproofd /etc/sysconfig/xproofd
    ln -s $ALICE_PROOF_AAF_PROOF_DIR/aaf-proof/scripts/xproofd.rc.d /etc/init.d/xproofd
    ln -s $ALICE_PROOF_AAF_PROOF_DIR/aaf-proof/scripts/xproofd.sysconfig /etc/sysconfig/xproofd

    RecreateAfdsmgrLinks
  else
    if [ "$DISTRIBUTION_NAME" == "GentooBase" ]; then
      echo "Gentoo"
        rm -f /etc/init.d/xproofd /etc/conf.d/xproofd
	ln -s $ALICE_PROOF_AAF_PROOF_DIR/aaf-proof/scripts/xproofd.rc.d /etc/init.d/xproofd
	ln -s $ALICE_PROOF_AAF_PROOF_DIR/aaf-proof/scripts/xproofd.sysconfig /etc/conf.d/xproofd

    RecreateAfdsmgrLinks
    else
      echo "Not supported Distribution"
      exit 1
    fi
  fi

#   InitProofPool $ALICE_PROOF_AAF_PROOF_DIR

}

function InstallAAFAsUser() {

  if [ ! -d $ALICE_PROOF_AAF_DIR ]; then
    echo "Directory \$ALICE_PROOF_AAF_DIR=$ALICE_PROOF_AAF_DIR doesn't exists !!!"
    exit 1
  fi

  echo "Installing AliEn ..."
  InstallAliEn
  if [ "$?" != "0" ];then
    echo "Error in installing AliEn !!!"
    exit 1
  fi
#   echo "Installing InstallXrootdVMSS ..."
#   InstallXrootdVMSS
#   if [ "$?" != "0" ];then
#     echo "Error in InstallXrootdVMSS !!!"
#     exit 2
#   fi
 
#   IsAliEnAndXrootdInstalled
#   if [ "$?" == "0" ]; then
#     echo "ALL OK"
#   fi
#   echo ""
}


function CleanAAF() {
  echo "Cleaning PROOF worker `hostname -f` ..."
  rm -Rf $ALICE_PROOF_AAF_DIR
  rm -Rf /tmp/ALICE 
  rm -Rf /tmp/xrd-installer-$ALICE_PROOF_AAF_USER
  rm -f /tmp/alien-installer > /dev/null 2>&1
  rm -f /tmp/xrd-installer > /dev/null 2>&1

  PrintAafInfo

}


function checkXrootdInstallation() {
# This function expects two arguments: 
# 1) xrootd installation directory path and
# 2) xrootd installation log file
# If there were warnings or failures during xrootd installation
# diagnostic message is saved in global variable xrootd_check_message 

  if [ $# -ne 2 ]; then
    echo "checkXrootdInstallation: Wrong number of parameters."
    echo "The function should be called as follows: checkXrootdInstallation <package name> <installation log file>"
    exit 1
  fi

  if [ ! -e $2 ]; then
    echo -e "xrootd installation failed - file $2 not found\n"
    echo_failure
  else
    if [ `grep -c -i -e 'make[[:space:]]\+failed' $2` -gt 0 ]; then
      if [ `grep -c -i -e 'post_install done with 0' $2` -gt 0 ]; then
        echo_warning
        echo "$xrootd_check_message$1: WARNING - $2\n"
      else
        echo_failure
        echo "$xrootd_check_message$1: FAILURE - $2\n"
      fi
    else
      echo_success
    fi
  fi
echo
}


function IsAliEnAndXrootdInstalled() {

  echo "Checking AliEn and Xrootd ..."
  if [ -e $ALICE_PROOF_AAF_DIR/alien/bin/alien ]; then
    echo "$ALICE_PROOF_AAF_DIR/alien/bin/alien found ..."
  else
    echo "$ALICE_PROOF_AAF_DIR/alien/bin/alien NOT found ..."
    return 1;
  fi
  if [ -e $ALICE_PROOF_AAF_DIR/alien/api/bin/xrdgsiproxy ]; then
    echo "$ALICE_PROOF_AAF_DIR/alien/api/bin/xrdgsiproxy found ..."
  else
    echo "$ALICE_PROOF_AAF_DIR/alien/api/bin/xrdgsiproxy NOT found ..."
    return 2;
  fi

  xrootd_ver=`ls $ALICE_PROOF_AAF_ALIEN_PACKAGES/${ALICE_PROOF_AAF_AAF_XROOTD_PACKAGE/@/\/}`
  checkXrootdInstallation "xrootd" "$ALICE_PROOF_AAF_ALIEN_PACKAGES/VO_ALICE.aaf-xrootd.$xrootd_ver.InstallLog"

  return 0
}

function InstallAliEn() {

  rm -Rf $ALICE_PROOF_AAF_ALIEN_DIR

  if [ -z "$ALICE_PROOF_AAF_ALIEN_SHARED_DIR" ]; then
    if [ "$1" == "REINSTALL" ]; then
      rm -f $ALICE_PROOF_AAF_ALIEN_DIR
    fi
    if [ ! -d $ALICE_PROOF_AAF_ALIEN_DIR ];then
      echo "Installing AliEn on node `hostname -f` ..."
      rm -f $ALICE_PROOF_AAF_TMP_DIR/alien-installer > /dev/null 2>&1
#       cd $ALICE_PROOF_AAF_TMP_DIR/ && wget http://alien.cern.ch/alien-installer && chmod +x alien-installer && ./alien-installer -install-dir $ALICE_PROOF_AAF_ALIEN_DIR -type vobox -version $ALICE_PROOF_AAF_ALIEN_VERSION -batch
      cd $ALICE_PROOF_AAF_TMP_DIR/ && wget http://alien.cern.ch/alien-installer && chmod +x alien-installer && ./alien-installer -install-dir $ALICE_PROOF_AAF_ALIEN_DIR -type vobox -version $MY_ALIEN_VER -batch
      cd $ALICE_PROOF_AAF_ALIEN_DIR/api && ln -s lib lib64
    fi
  else
    echo "Using AliEn from $ALICE_PROOF_AAF_ALIEN_SHARED_DIR ..."
    if [ "$1" == "REINSTALL" ]; then
      rm -f $ALICE_PROOF_AAF_ALIEN_SHARED_DIR
    fi
    if [ ! -d $ALICE_PROOF_AAF_ALIEN_SHARED_DIR ];then
      echo "Installing shared AliEn on node `hostname -f` ..."
      rm -f $ALICE_PROOF_AAF_TMP_DIR/alien-installer > /dev/null 2>&1
#       cd $ALICE_PROOF_AAF_TMP_DIR/ && wget http://alien.cern.ch/alien-installer && chmod +x alien-installer && ./alien-installer -install-dir $ALICE_PROOF_AAF_ALIEN_SHARED_DIR -type vobox -version $ALICE_PROOF_AAF_ALIEN_VERSION -batch
      cd $ALICE_PROOF_AAF_TMP_DIR/ && wget http://alien.cern.ch/alien-installer && chmod +x alien-installer && ./alien-installer -install-dir $ALICE_PROOF_AAF_ALIEN_SHARED_DIR -type vobox -version $MY_ALIEN_VER -batch
      cd $ALICE_PROOF_AAF_ALIEN_SHARED_DIR/api && ln -s lib lib64
      ln -s $ALICE_PROOF_AAF_ALIEN_SHARED_DIR $ALICE_PROOF_AAF_ALIEN_DIR
    else
      ln -s $ALICE_PROOF_AAF_ALIEN_SHARED_DIR $ALICE_PROOF_AAF_ALIEN_DIR
    fi

  fi

}


function ReInstallAliEn() {

  InstallAliEn

}

function AliEnInit() {
  
  echo "AliEn sync started at `date` ..."

	ClearTmpDirectory

#   if [ ! -d $ALICE_PROOF_AAF_DIR/.globus/usercert.pem]; then
#     echo "Error : $ALICE_PROOF_AAF_CERTGLOBUS_DIR is missing !!!"
#     exit 1
#   fi

  if [ ! -d $ALICE_PROOF_AAF_DIR/.globus ];then
    if [ -d $ALICE_PROOF_AAF_CERTGLOBUS_DIR ]; then
      cp -R $ALICE_PROOF_AAF_CERTGLOBUS_DIR $ALICE_PROOF_AAF_DIR/.globus
    fi
  fi

  if [ ! -e $ALICE_PROOF_AAF_DIR/.globus/usercert.pem ]; then
    echo "Error : $ALICE_PROOF_AAF_DIR/.globus/usercert.pem is missing !!!"
    exit 1
  fi
  if [ ! -e $ALICE_PROOF_AAF_DIR/.globus/userkey.pem ]; then
    echo "Error : $ALICE_PROOF_AAF_DIR/.globus/userkey.pem is missing !!!"
    exit 2
  fi

  if [ "`whoami`" != "$ALICE_PROOF_AAF_USER" ]; then
    echo "Error : You have to run it as '$ALICE_PROOF_AAF_USER' user and not as '`whoami`' !!!!"
    exit 3
  fi

#   if [ ! -d $ALICE_PROOF_AAF_ALIEN_PACKAGES ]; then
#     mkdir $ALICE_PROOF_AAF_ALIEN_PACKAGES
#   fi

  echo "Sync AliEn Packages on `hostname -f` ..."
#   echo "Doing $ALICE_PROOF_AAF_DIR/alien/bin/alien proxy-init -cert $ALICE_PROOF_AAF_DIR/.globus/usercert.pem -key $ALICE_PROOF_AAF_DIR/.globus/userkey.pem ..."
  AliEnCreateProxy  

  $ALICE_PROOF_AAF_DIR/alien/bin/alien -user proof -exec packman list $AAF_PACKMAN_SOURCE
  if [ "$?" != "0" ]; then
    echo "Cannot talk to alien. Try later !!!!"
    AliEnDestroyProxy
    exit 5
  fi
}

function AliEnPostInstall() {

    # uninstall + install AAF-ALIROOT (when instaltion is done post scripts is run and it will refresh all aliroot version for proof packages)
    TMP_AAF_NAME=$ALICE_PROOF_AAF_AAF_ALIROOT_PACKAGE
    TMP_AAF_NAME=${TMP_AAF_NAME/@/\/}
    rm -Rf $ALICE_PROOF_AAF_ALIEN_PACKAGES/$TMP_AAF_NAME
    $ALICE_PROOF_AAF_DIR/alien/bin/alien -user proof -exec packman synchronize -local -dir $ALICE_PROOF_AAF_ALIEN_PACKAGES -packages $ALICE_PROOF_AAF_AAF_ALIROOT_PACKAGE $AAF_PACKMAN_SOURCE
    CreateDepFile "aliroot" "$ALICE_PROOF_AAF_ALIEN_PACKAGES/deps" "NoPROXY"
    echo ""
    echo "========= Installed AliEn Packages =========="
    $ALICE_PROOF_AAF_DIR/alien/bin/alien -user proof -exec packman listInstalled -local -dir $ALICE_PROOF_AAF_ALIEN_PACKAGES $AAF_PACKMAN_SOURCE
    echo "============================================="
    
    
    IsAliEnAndXrootdInstalled
    if [ "$?" == "0" ]; then
	echo "ALL OK"
    fi
    echo ""
    
    echo "Cleaning AliEn cache ..."
    rm -Rf $ALICE_PROOF_AAF_TMP_DIR/alien/ALICE/*
    
  echo "Cleaning XRDDM log files older then 7 days ..."
  if [ -d $ALICE_PROOF_AAF_DIR/logs/xrddm/ ]; then
      find $ALICE_PROOF_AAF_DIR/logs/xrddm/ -type f -atime +7 -exec rm -f {} \;
      find $ALICE_PROOF_AAF_DIR/logs/xrddm/ -depth -type d -empty -exec rmdir {} \;
  fi
  mv $ALICE_PROOF_AAF_DIR/logs/xrddm.log $ALICE_PROOF_AAF_DIR/logs/xrddm.log.tmp
  tail -n 1000 $ALICE_PROOF_AAF_DIR/logs/xrddm.log.tmp > $ALICE_PROOF_AAF_DIR/logs/xrddm.log
  rm -f $ALICE_PROOF_AAF_DIR/logs/xrddm.log.tmp

  if [ "${AF_ALIROOT_DIR_TEMPLATE:0:6}" != "/cvmfs" ]; then
      AliEnDestroyProxy
  fi

  
}

function AliEnCreateProxy() {

  $ALICE_PROOF_AAF_DIR/alien/bin/alien proxy-init -cert $ALICE_PROOF_AAF_DIR/.globus/usercert.pem -key $ALICE_PROOF_AAF_DIR/.globus/userkey.pem
  if [ "$?" != "0" ]; then
    echo "alien proxy-init error !!!!"
    AliEnDestroyProxy
    exit 4
  fi
}

function AliEnDestroyProxy() {
  $ALICE_PROOF_AAF_DIR/alien/bin/alien proxy-destroy
}

function AliEnPackagesSync() {

    AliEnInit

    if [ "${AF_ALIROOT_DIR_TEMPLATE:0:6}" = "/cvmfs" ]; then
	# UpgradeAAF
	AliEnPostInstall
	return 0
    fi

  $ALICE_PROOF_AAF_DIR/alien/bin/alien -user proof -exec packman list -force $AAF_PACKMAN_SOURCE


  if [ -n "$ALICE_PROOF_AAF_AAF_ALICESOFT_SHARED_DIR" ]; then

    if [ ! -d $ALICE_PROOF_AAF_AAF_ALICESOFT_SHARED_DIR ]; then
      echo "ALICE_PROOF_AAF_AAF_ALICESOFT_SHARED_DIR = $ALICE_PROOF_AAF_AAF_ALICESOFT_SHARED_DIR is not created !!!!"
      AliEnDestroyProxy
      exit 1
    fi

    if [ ! -L $ALICE_PROOF_AAF_AAF_ALICESOFT_SHARED_DIR/VO_ALICE ]; then
      rm -Rf $ALICE_PROOF_AAF_ALIEN_PACKAGES
      mkdir -p $ALICE_PROOF_AAF_ALIEN_PACKAGES
      mkdir -p $ALICE_PROOF_AAF_AAF_ALICESOFT_SHARED_DIR/VO_ALICE
      ln -s $ALICE_PROOF_AAF_AAF_ALICESOFT_SHARED_DIR/VO_ALICE $ALICE_PROOF_AAF_ALIEN_PACKAGES/VO_ALICE
    fi

    rm -Rf $ALICE_PROOF_AAF_DIR/tmp/alien/ALICE
    if [ ! -d $ALICE_PROOF_AAF_AAF_ALICESOFT_SHARED_DIR/tmp/alien/ALICE ]; then
      mkdir -p $ALICE_PROOF_AAF_AAF_ALICESOFT_SHARED_DIR/tmp/alien/ALICE
    fi
    ln -s $ALICE_PROOF_AAF_AAF_ALICESOFT_SHARED_DIR/tmp/alien/ALICE $ALICE_PROOF_AAF_DIR/tmp/alien/ALICE

  else 
    if [ ! -d $ALICE_PROOF_AAF_ALIEN_PACKAGES ]; then
      mkdir $ALICE_PROOF_AAF_ALIEN_PACKAGES
    fi
#     rm -Rf $ALICE_PROOF_AAF_DIR/tmp/alien/ALICE
#     mkdir -p $ALICE_PROOF_AAF_DIR/tmp/alien/ALICE
  fi

	rmdir $ALICE_PROOF_AAF_ALIEN_PACKAGES/VO_ALICE/ROOT/*  > /dev/null 2>&1
	rmdir $ALICE_PROOF_AAF_ALIEN_PACKAGES/VO_ALICE/AliRoot/*  > /dev/null 2>&1
  # sync ROOT + ALIROOT
  $ALICE_PROOF_AAF_DIR/alien/bin/alien -user proof -exec packman synchronize -local -dir $ALICE_PROOF_AAF_ALIEN_PACKAGES -packages $ALICE_PROOF_AAF_AAF_ALICESOFT_PACKAGE $AAF_PACKMAN_SOURCE

  AliEnPostInstall
}

function UpdateParsFromCVMFS() {
    ALIROOT_VERS_DIR=$(ls "${AF_ALIROOT_DIR_TEMPLATE/<VERSION>/}")
    for MY_VER in $ALIROOT_VERS_DIR; do
	echo "$MY_VER"
	if [ ! -f $ALICE_PROOF_AAF_PROOF_DIR/packages/${MY_VER}.par ]; then
	    mkdir -p $ALICE_PROOF_AAF_PROOF_DIR/packages/VO_ALICE@AliRoot::$MY_VER
	    cp -r $ALICE_PROOF_AAF_PROOF_DIR/aaf-aliroot/aaf-aliroot/PROOF-INF/VO_ALICE@AliRoot_CVMFS/PROOF-INF/ $ALICE_PROOF_AAF_PROOF_DIR/packages/VO_ALICE@AliRoot::$MY_VER/PROOF-INF
	    HERETMP=`pwd`
	    cd $ALICE_PROOF_AAF_PROOF_DIR/packages
	    tar cf - "VO_ALICE@AliRoot::$MY_VER" | gzip -f9 > "VO_ALICE@AliRoot::$MY_VER.par"
	    rm -Rf "VO_ALICE@AliRoot::$MY_VER"
	    cd $HERETMP
	fi
    done

}

function UpdateProofPackages() {
    
    if [ "$ALICE_PROOF_AAF_PROOF_MASTER" == "`hostname -f`" ]; then
	
	if [ "$2" != "" ]; then
	    echo "Sleeping $2 sec before UpdateProofPackages ..."
	    sleep $2
	fi
	export AAF_DIR="$ALICE_PROOF_AAF_DIR"
	
	S=""
	if [ "${AF_ALIROOT_DIR_TEMPLATE:0:6}" = "/cvmfs" ]; then
	    source /cvmfs/alice.cern.ch/etc/login.sh
	    UpdateParsFromCVMFS
	    alienv setenv AliEn -c xrdgsiproxy -cert $AAF_DIR/.globus/usercert.pem -key $AAF_DIR/.globus/userkey.pem init
	    ROOT_CMD="alienv setenv AliEn,AliRoot -c root"
	    S='\'
	else
	    source $ALICE_PROOF_AAF_DIR/scripts/env_aliroot_aaf.bash "" ""
	    xrdgsiproxy -cert $AAF_DIR/.globus/usercert.pem -key $AAF_DIR/.globus/userkey.pem init
	    ROOT_CMD="root"
	fi
	echo "Running $ROOT_CMD"

	if [ "$3" != "" ]; then
	    echo "Rebuilding ALL proof packages ..."
	    echo "$ROOT_CMD "
            #$ROOT_CMD -b -q -l \$ALICE_PROOF_AAF_DIR'/macros/EnableGlobalParFile.C("'\$ALICE_PROOF_AAF_USER'@'\$ALICE_PROOF_AAF_PROOF_MASTER'","","","CLEARALL")'

	    $ROOT_CMD -b -q -l $ALICE_PROOF_AAF_DIR/macros/EnableGlobalParFile.C$S\($S\"$ALICE_PROOF_AAF_USER@$ALICE_PROOF_AAF_PROOF_MASTER$S\",$S\"$S\",$S\"$S\",$S\"CLEARALL$S\"$S\)
	    RET="$?"
	    if [ "$RET" != "0" ]; then
		echo "Error in EnableGlobalParFile.C macro !!!!!!"
		return 2
	    fi
	else
	    # clear removed par files
	    for PARFILE  in `ls $ALICE_PROOF_AAF_PROOF_DIR/proofbox/$ALICE_PROOF_AAF_USER/packages/*.par`; do
		PARFILE=`basename $PARFILE`
		LS_RET=`ls $ALICE_PROOF_AAF_PROOF_DIR/packages/$PARFILE > /dev/null 2>&1`
		RET="$?"
		if [ "$RET" != "0" ]; then
		    echo "Clearing package $PARFILE ..."
		    $ROOT_CMD -b -q -l $ALICE_PROOF_AAF_DIR/macros/EnableGlobalParFile.C$S\($S\"$ALICE_PROOF_AAF_USER@$ALICE_PROOF_AAF_PROOF_MASTER$S\",$S\"$PARFILE$S\",$S\"$S\",$S\"CLEARPACKAGE$S\"$S\)
		    echo "Package $PARFILE removed ..."
		fi
	    done
	fi
	# append new parfile
	for PARFILE  in `ls $ALICE_PROOF_AAF_PROOF_DIR/packages`; do
	    LS_RET=`ls $ALICE_PROOF_AAF_PROOF_DIR/proofbox/$ALICE_PROOF_AAF_USER/packages/$PARFILE > /dev/null 2>&1`
	    RET="$?"
	    if [ "$RET" != "0" ]; then
		# try to find correct ROOT
		PARFILE_ONLY_PACKAGE=$PARFILE
		PARFILE_ONLY_PACKAGE=${PARFILE_ONLY_PACKAGE/.par/}
		if [ "${AF_ALIROOT_DIR_TEMPLATE:0:6}" = "/cvmfs" ]; then
		    PARFILE_ONLY_PACKAGE_NAME=${PARFILE_ONLY_PACKAGE//VO_ALICE@/}
		    PARFILE_ONLY_PACKAGE_NAME=${PARFILE_ONLY_PACKAGE_NAME//_CVMFS/}
		    if [ "${PARFILE_ONLY_PACKAGE_NAME:0:7}" = "AliRoot" ];then
			PARFILE_ONLY_PACKAGE_NAME=${PARFILE_ONLY_PACKAGE_NAME//::/\/}
			ROOT_CMD="alienv setenv AliEn,$PARFILE_ONLY_PACKAGE_NAME -c root.exe"
			MYROOT_VER_ALIROOT="VO_ALICE@ROOT::"$(alienv setenv AliEn,$PARFILE_ONLY_PACKAGE_NAME -c basename \$ROOTSYS)
		    else
			ROOT_CMD="alienv setenv AliEn,AliRoot -c root"
			MYROOT_VER_ALIROOT="VO_ALICE@ROOT::current"
		    fi

		else
		    MYROOT_VER_ALIROOT=`cat $ALICE_PROOF_AAF_ALIEN_PACKAGES/deps/aliroot_deps.txt | grep "$PARFILE_ONLY_PACKAGE|" | awk -F '|' '{print $2}'`
		fi
		echo "Adding package $PARFILE with ROOT $MYROOT_VER_ALIROOT in $1 sec ($ROOT_CMD)..."
		# echo "$ROOT_CMD -b -q -l $ALICE_PROOF_AAF_DIR/macros/EnableGlobalParFile.C$S\($S\"$ALICE_PROOF_AAF_USER@$ALICE_PROOF_AAF_PROOF_MASTER$S\",$S\"$ALICE_PROOF_AAF_PROOF_DIR/packages/$PARFILE$S\",$S\"$MYROOT_VER_ALIROOT$S\"$S\)"
		sleep $1
		$ROOT_CMD -b -q -l $ALICE_PROOF_AAF_DIR/macros/EnableGlobalParFile.C$S\($S\"$ALICE_PROOF_AAF_USER@$ALICE_PROOF_AAF_PROOF_MASTER$S\",$S\"$ALICE_PROOF_AAF_PROOF_DIR/packages/$PARFILE$S\",$S\"$MYROOT_VER_ALIROOT$S\"$S\)
		RET="$?"
		if [ "$RET" != "0" ]; then
		    # clears package
		    echo "Clearing package $PARFILE ..."
		    echo "Sleeping for $1 sec ..."
		    sleep $1
		    $ROOT_CMD -b -q -l $ALICE_PROOF_AAF_DIR/macros/EnableGlobalParFile.C$S\($S\"$ALICE_PROOF_AAF_USER@$ALICE_PROOF_AAF_PROOF_MASTER$S\",$S\"$PARFILE$S\",$S\"$S\",$S\"CLEARPACKAGE$S\"$S\)
		    echo "Package $PARFILE removed ..."
		else
		    echo "Package $PARFILE added ..."
		fi
		
	    fi
	done
    else
	echo "You are not running it on master ($ALICE_PROOF_AAF_PROOF_MASTER)!!!!!!!"
	return 1
    fi
    
    echo "UpdateProofPackages was OK ..."
}

function CheckPackagesInstallation() {

# This function checks that certain directories on (single) master are present on workers and have identical content for up to second-level subdirectories and files only!.
# It has the following arguments:
# $1 - the file in proof format containing the list of master and workers. If "" is passed then $ALICE_PROOF_AAF_PROOF_XPROOFD_DIR/proof.conf is used;
# $2 - (string) list of directories (on master) to be checked across the workers. The directory names are separated by space;
# $3 - number of retries;
# $4 - time in seconds to sleep between attempts to retry.

if [ "$ALICE_PROOF_AAF_PROOF_MASTER" != "`hostname -f`" ]; then
  echo "You are not running it on master ($ALICE_PROOF_AAF_PROOF_MASTER)!!!!!!!"
  exit 9
fi

if [ $# -ne 4 ]; then
   echo "CheckPackagesInstallation: wrong number of parameters!"
   exit 9
fi

if [ -n "$1" ]; then
  nodelist_file="$1"
else
  nodelist_file="$ALICE_PROOF_AAF_PROOF_XPROOFD_DIR/proof.conf"
fi

if [ ! -e "$nodelist_file" ]; then
  echo "No file with the list of master and worker nodes is provided !!!"
  exit 9
fi

m=`grep "master" $nodelist_file`
m=${m##master }
ws=( `grep "worker" $nodelist_file | sort | uniq | sed "s/worker //"` )

dirlist=( $2 )

for (( i=1; i<=$3; i+=1 ))
do
  status="PASS"
  echo "************ Packages installation check ************"
  echo "Attempt #$i"
  echo "Date: `date`"

  masterlist=""
  for d in ${dirlist[@]}
  do
    masterlist=( "$masterlist `find $d -maxdepth 2 -type d -print | sort`" )
  done

  workerlist=""

  for w in ${ws[@]}
  do
    echo
    echo "Checking worker $w"
    for dr in ${masterlist[@]}
    do
      echo -n "  $dr: "
      if [ -n "`ssh $w \"ls $dr\" 2>/dev/null `" ]; then
        echo "OK"
      else
        echo -e "NOT FOUND"
        status="FAILED"
      fi
    done
  done
  echo
  
  if [ "$i" -lt "$3" ]; then
    sleep $4
  fi
done

if [ "x$status" = "xFAILED" ]; then
  return 9
else
  return 0
fi

}

function UpgradeAAF() {

  AliEnInit

  $ALICE_PROOF_AAF_DIR/alien/bin/alien -user proof -exec packman list -force $AAF_PACKMAN_SOURCE

  # uninstall + install AAF-ALIROOT (when instaltion is done post scripts is run and it will refresh all aliroot version for proof packages)
  TMP_AAF_NAME=$ALICE_PROOF_AAF_AAF_ALIROOT_PACKAGE
  TMP_AAF_NAME=${TMP_AAF_NAME/@/\/}
  rm -Rf $ALICE_PROOF_AAF_ALIEN_PACKAGES/$TMP_AAF_NAME
  $ALICE_PROOF_AAF_DIR/alien/bin/alien -user proof -exec packman synchronize -local -dir $ALICE_PROOF_AAF_ALIEN_PACKAGES -packages $ALICE_PROOF_AAF_AAF_ALIROOT_PACKAGE $AAF_PACKMAN_SOURCE


  # sync AAF-PROOFBOX_DIR
  $ALICE_PROOF_AAF_DIR/alien/bin/alien -user proof -exec packman synchronize -local -dir $ALICE_PROOF_AAF_ALIEN_PACKAGES -packages $ALICE_PROOF_AAF_AAF_PROOF_PACKAGE $AAF_PACKMAN_SOURCE

  # sync AAF-XROOTD
  $ALICE_PROOF_AAF_DIR/alien/bin/alien -user proof -exec packman synchronize -local -dir $ALICE_PROOF_AAF_ALIEN_PACKAGES -packages $ALICE_PROOF_AAF_AAF_XROOTD_PACKAGE $AAF_PACKMAN_SOURCE

  AliEnPostInstall

  UpdateSettingWithAAFConfig

}

function ModifyRootsysInProofconfig() {


  MY_PROOF_CF_FILE_TMP="$ALICE_PROOF_AAF_PROOF_XPROOFD_DIR/prf-main.cf.new.rootsys"
  

  # remove all rootsys form prf-main.cf
  cat $ALICE_PROOF_AAF_PROOF_XPROOFD_DIR/prf-main.cf | grep -v 'xpd.rootsys' > $MY_PROOF_CF_FILE_TMP

  # add defaullt root sys
#   echo "" >> $MY_PROOF_CF_FILE_TMP
#   echo "# default root and root dbg" >> $MY_PROOF_CF_FILE_TMP
  echo "xpd.rootsys \$gRootsys VO_ALICE@ROOT::current" >> $MY_PROOF_CF_FILE_TMP
  echo "xpd.rootsys \$gRootsys current" >> $MY_PROOF_CF_FILE_TMP
#   echo "xpd.rootsys \$gRootsysDbg current_dbg" >> $MY_PROOF_CF_FILE_TMP
#   echo "" >> $MY_PROOF_CF_FILE_TMP

  # add other available root versions
  if [ ! -z $1 ];then
      MY_ALIEN_USER=`echo $1 | awk -F '@' '{print $1}'`
      MY_ALIEN_PACKAGE=`echo $1 | awk -F '@' '{print $2}'`
	  
      if [ "${AF_ALIROOT_DIR_TEMPLATE:0:6}" = "/cvmfs" ]; then
	  MY_ROOT_DIR=$(dirname $AF_ALIROOT_DIR_TEMPLATE)
	  MY_ROOT_DIR=$(dirname $MY_ROOT_DIR)
	  MY_ROOT_DIR="$MY_ROOT_DIR/ROOT"
	  if [ -d $MY_ROOT_DIR ];then
	      for MY_VER  in `ls $MY_ROOT_DIR`; do
                  echo "xpd.rootsys $MY_ROOT_DIR/$MY_VER $MY_ALIEN_USER@$MY_ALIEN_PACKAGE::$MY_VER" >> $MY_PROOF_CF_FILE_TMP
	      done
	  fi
      else
	  if [ -d $ALICE_PROOF_AAF_ALIEN_PACKAGES/$MY_ALIEN_USER/$MY_ALIEN_PACKAGE/ ]; then
	      #       echo "# additional root versions" >> $MY_PROOF_CF_FILE_TMP
	      for MY_VER  in `ls $ALICE_PROOF_AAF_ALIEN_PACKAGES/$MY_ALIEN_USER/$MY_ALIEN_PACKAGE/`; do
		  echo "xpd.rootsys $ALICE_PROOF_AAF_ALIEN_PACKAGES/$MY_ALIEN_USER/$MY_ALIEN_PACKAGE/$MY_VER/$MY_VER $MY_ALIEN_USER@$MY_ALIEN_PACKAGE::$MY_VER" >> $MY_PROOF_CF_FILE_TMP
	      done
	  fi
      fi
      cp -f $MY_PROOF_CF_FILE_TMP $ALICE_PROOF_AAF_PROOF_XPROOFD_DIR/prf-main.cf
  else
      echo "Empty package name !!!"
  fi  

}

function UpdateSettingWithAAFConfig() {
 	$ALICE_PROOF_AAF_DIR/scripts/xproofd.sh $ALICE_PROOF_AAF_PROOF_XPROOFD_DIR/
#	$ALICE_PROOF_AAF_PROOF_XPROOFD_DIR/xproofd.sh $ALICE_PROOF_AAF_PROOF_XPROOFD_DIR/
	ModifyRootsysInProofconfig VO_ALICE@ROOT
}

function InstallXrootdVMSS() {
  rm -f /tmp/xrd-installer > /dev/null 2>&1

  if [ ! -d $ALICE_PROOF_AAF_DIR/xrootd ];then
    
    cd $ALICE_PROOF_AAF_TMP_DIR/ && wget http://project-arda-dev.web.cern.ch/project-arda-dev/xrootd/tarballs/installbox/xrd-installer && chmod +x xrd-installer
    cd $ALICE_PROOF_AAF_TMP_DIR/ && ./xrd-installer --prefix=$ALICE_PROOF_AAF_DIR/xrootd --version=$ALICE_PROOF_AAF_XROOTD_VERSION --install


    mv $ALICE_PROOF_AAF_DIR/xrootd/etc/xrootd/system.cnf $ALICE_PROOF_AAF_DIR/xrootd/etc/xrootd/system.cnf.orig
    if [ "$ALICE_PROOF_AAF_XROOTD_SYSTEM_CN" != "$ALICE_PROOF_AAF_DIR/xrootd/etc/xrootd/system.cnf" ]; then
      ln -s $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN $ALICE_PROOF_AAF_DIR/xrootd/etc/xrootd/system.cnf
    fi
    rm -f /tmp/xrd-installer > /dev/null 2>&1
  else
    echo "Xrootd SE exist already in $ALICE_PROOF_AAF_DIR/xrootd. Skipping ..."
  fi

}

function ReInstallXrootdVMSS() {

#  InitXrootdVMSS
echo "Not Working yet "

}

function ReInstallXrootdDm() {

#  InitXrootdVMSS
echo "Not Working yet "

}

function InitXrootdVMSS() {

  if [ ! -d $ALICE_PROOF_AAF_DIR/backup ];then
    mkdir -p $ALICE_PROOF_AAF_DIR/backup/proc/sys/fs/
    mkdir -p $ALICE_PROOF_AAF_DIR/backup/etc/security

    BackupOneFile /proc/sys/fs/file-max $ALICE_PROOF_AAF_DIR/backup/proc/sys/fs/file-max
    BackupOneFile /etc/sysctl.conf $ALICE_PROOF_AAF_DIR/backup/etc/sysctl.conf
    BackupOneFile /etc/security/limits.conf $ALICE_PROOF_AAF_DIR/backup/etc/security/limits.conf

    chown -R $ALICE_PROOF_AAF_USER:$ALICE_PROOF_AAF_GROUP $ALICE_PROOF_AAF_DIR/backup/

    cur_lim_file_max=`cat /proc/sys/fs/file-max`
    if [ -n "$cur_lim_file_max" ]; then
      if [ "$cur_lim_file_max" -lt "65535" ]; then
        echo 65535 > /proc/sys/fs/file-max
        echo "fs.file-max = 65535" >> /etc/sysctl.conf
      fi
    fi
    echo "net.core.rmem_max = 8388608" >> /etc/sysctl.conf
    echo "net.core.wmem_max = 8388608" >> /etc/sysctl.conf
    echo "net.ipv4.tcp_rmem = 4096 87380 8388608" >> /etc/sysctl.conf
    echo "net.ipv4.tcp_wmem = 4096 65536 8388608" >> /etc/sysctl.conf
    echo "net.core.netdev_max_backlog = 250000" >> /etc/sysctl.conf
    echo "net.ipv4.tcp_timestamps=0" >> /etc/sysctl.conf

    echo "* - nofile 65535" >> /etc/security/limits.conf
  fi

  if [ "x$ALICE_PROOF_AAF_XROOTD_XRDNAMESPACE" != "x" ]; then
    mkdir -p $ALICE_PROOF_AAF_XROOTD_XRDNAMESPACE
    chown $ALICE_PROOF_AAF_USER:$ALICE_PROOF_AAF_GROUP $ALICE_PROOF_AAF_XROOTD_XRDNAMESPACE
  fi

  if [ "x$ALICE_PROOF_AAF_XROOTD_XRDDATA" != "x" ]; then
    for XRDDATA_DIR in $ALICE_PROOF_AAF_XROOTD_XRDDATA; do
      echo 
      mkdir -p $XRDDATA_DIR
      chown $ALICE_PROOF_AAF_USER:$ALICE_PROOF_AAF_GROUP $XRDDATA_DIR
    done
  fi
}

function SetupXrootdVMSSRedirector() {

#   mkdir -p $ALICE_PROOF_AAF_DIR/xrootd_conf/

  echo "export MANAGERHOST=\"\`hostname -f\`\"" > $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  if [ -z "$1" ]; then
    echo "export SERVERONREDIRECTOR=\"0\"" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  else
    echo "export SERVERONREDIRECTOR=\"1\"" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  fi
  echo "export MONALISA_HOST='$ALICE_PROOF_AAF_XROOTD_MONALISA'" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

  echo "export SE_NAME=\"$ALICE_PROOF_AAF_XROOTD_SE_NAME\"" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

  echo "export XRDDEBUG=\"\"" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

  echo "export XRDUSER=\"$ALICE_PROOF_AAF_USER\"" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

  echo "export XRDMAXFD=65000" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

  echo "export XRDBASEDIR=\"\"" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

  echo "export SYSTEM=XROOTD" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  if [ -z "$1" ]; then
    echo "export XRDSERVERPORT=1094" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
    echo "export XRDMANAGERPORT=1094" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
    echo "export CMSDSERVERPORT=3122" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
    echo "export CMSDMANAGERPORT=3122" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  else
#     echo 'if [ "x\$SERVERONREDIRECTOR" = "x1" ]; then' >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
    echo "   export XRDSERVERPORT=1095" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
    echo "   export XRDMANAGERPORT=1094" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
    echo "   export CMSDSERVERPORT=3123" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
    echo "   export CMSDMANAGERPORT=3122" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
#     echo "fi" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  fi
  echo "#export ACCLIB=libXrdAliceTokenAcc.so" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

  echo "export METAMGRHOST=alice-gr01.cern.ch" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  echo "export METAMGRPORT=1213" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  echo "export VMSS_SOURCE=root://\${METAMGRHOST}/">> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

#   echo "#export LOCALPATHPFX=''" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

##  # creates direcotries for xrdnamespace
#  mkdir -p $ALICE_PROOF_AAF_XROOTD_XRDNAMESPACE
#  chown $ALICE_PROOF_AAF_USER:$ALICE_PROOF_AAF_GROUP $ALICE_PROOF_AAF_XROOTD_XRDNAMESPACE
#  echo "export LOCALROOT=\"$ALICE_PROOF_AAF_XROOTD_XRDNAMESPACE\"" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN


  if [ -z "$1" ]; then
    echo "export LOCALROOT=\"\"" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
    echo "export OSSCACHE=''" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  else
    mkdir -p $ALICE_PROOF_AAF_XROOTD_XRDNAMESPACE
    chown $ALICE_PROOF_AAF_USER:$ALICE_PROOF_AAF_GROUP $ALICE_PROOF_AAF_XROOTD_XRDNAMESPACE
    echo "export LOCALROOT=\"$ALICE_PROOF_AAF_XROOTD_XRDNAMESPACE\"" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  
    # creates direcotries for xrddata todo
    echo -n "export OSSCACHE='" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
    for XRDDATA_DIR in $ALICE_PROOF_AAF_XROOTD_XRDDATA; do
      echo 
      mkdir -p $XRDDATA_DIR
      chown $ALICE_PROOF_AAF_USER:$ALICE_PROOF_AAF_GROUP $XRDDATA_DIR
      echo -n "oss.cache public $XRDDATA_DIR\\n" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
    done
    echo "'" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  fi

  chown $ALICE_PROOF_AAF_USER:$ALICE_PROOF_AAF_GROUP $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

}
function SetupXrootdVMSSServer() {

#   mkdir -p $ALICE_PROOF_AAF_DIR/xrootd_conf/

  echo "export MANAGERHOST=\"$ALICE_PROOF_AAF_XROOTD_REDIRECTOR\"" > $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  # creates direcotries for xrdnamespace
  echo "export SERVERONREDIRECTOR=\"0\"" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

  echo "export MONALISA_HOST='$ALICE_PROOF_AAF_XROOTD_MONALISA'" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

  echo "export SE_NAME=\"$ALICE_PROOF_AAF_XROOTD_SE_NAME\"" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

  echo "export XRDDEBUG=\"\"" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

  echo "export XRDUSER=\"$ALICE_PROOF_AAF_USER\"" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

  echo "export XRDMAXFD=65000" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

  echo "export XRDBASEDIR=\"\"" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
#   echo "export XRDBASEDIR=\"$ALICE_PROOF_AAF_DIR/logs/xrootd\"" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

  echo "export SYSTEM=XROOTD" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

  echo "export XRDSERVERPORT=1094" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  echo "export XRDMANAGERPORT=1094" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  echo "export CMSDSERVERPORT=3122" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  echo "export CMSDMANAGERPORT=3122" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
#   echo "if [ "x$SERVERONREDIRECTOR" = "x1" ]; then" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
#   echo "   export XRDSERVERPORT=1095" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
#   echo "   export XRDMANAGERPORT=1094" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
#   echo "   export CMSDSERVERPORT=3123" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
#   echo "   export CMSDMANAGERPORT=3122" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
#   echo "fi" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

  echo "#export ACCLIB=libXrdAliceTokenAcc.so" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

  echo "export METAMGRHOST=alice-gr01.cern.ch" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  echo "export METAMGRPORT=1213" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  echo "export VMSS_SOURCE=root://\${METAMGRHOST}/">> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

#   echo "#export LOCALPATHPFX=''" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

  mkdir -p $ALICE_PROOF_AAF_XROOTD_XRDNAMESPACE
  chown $ALICE_PROOF_AAF_USER:$ALICE_PROOF_AAF_GROUP $ALICE_PROOF_AAF_XROOTD_XRDNAMESPACE
  echo "export LOCALROOT=\"$ALICE_PROOF_AAF_XROOTD_XRDNAMESPACE\"" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  
  # creates direcotries for xrddata todo
  echo -n "export OSSCACHE='" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  for XRDDATA_DIR in $ALICE_PROOF_AAF_XROOTD_XRDDATA; do
    echo 
    mkdir -p $XRDDATA_DIR
    chown $ALICE_PROOF_AAF_USER:$ALICE_PROOF_AAF_GROUP $XRDDATA_DIR
    echo -n "oss.cache public $XRDDATA_DIR\\n" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
  done
  echo "'" >> $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN

  chown $ALICE_PROOF_AAF_USER:$ALICE_PROOF_AAF_GROUP $ALICE_PROOF_AAF_XROOTD_SYSTEM_CN
}

function SetupPROOF() {

  # TODO port from aaf-init-proof-pool.sh

  if [ ! -d $ALICE_PROOF_AAF_PROOF_DIR ]; then
    mkdir -p $ALICE_PROOF_AAF_PROOF_DIR
  fi

  InitProofPool $ALICE_PROOF_AAF_PROOF_DIR

  if [ ! -d $ALICE_PROOF_AAF_PROOF_XPROOFD_DIR ]; then
    mkdir -p $ALICE_PROOF_AAF_PROOF_XPROOFD_DIR
  fi

#   cd $ALICE_PROOF_AAF_PROOF_XPROOFD_DIR
#   TMP_AAF_NAME=$ALICE_PROOF_AAF_AAF_PACKAGE
#   TMP_AAF_NAME=${TMP_AAF_NAME/@/\/}
#   TMP_AAF_NAME=${TMP_AAF_NAME/::/\/}

}

function InitProofPool() {

  if [ ! -z "$1" ]; then
    POOL_DIR="$1/pool"
    ADMIN_DIR="$POOL_DIR/admin"
    PROOFBOX_DIR="$POOL_DIR/proofbox"
    DATASET_DIR="$POOL_DIR/dataset"

    rm -Rf $POOL_DIR > /dev/null 2>&1

    mkdir -p $POOL_DIR
    mkdir -p $ADMIN_DIR
    mkdir -p $PROOFBOX_DIR
    mkdir -p $DATASET_DIR

    chown $ALICE_PROOF_AAF_USER:$ALICE_PROOF_AAF_GROUP $POOL_DIR

    # admin dir
    chown $ALICE_PROOF_AAF_USER:$ALICE_PROOF_AAF_GROUP $ADMIN_DIR
    chmod 755 $ADMIN_DIR

    # proofbox
    chown $ALICE_PROOF_AAF_USER:$ALICE_PROOF_AAF_GROUP $PROOFBOX_DIR

    # dataset 
    mkdir -p $DATASET_DIR

    mkdir -p $DATASET_DIR/default
    mkdir -p $DATASET_DIR/COMMON/COMMON

    chown $ALICE_PROOF_AAF_USER:$ALICE_PROOF_AAF_GROUP $DATASET_DIR
    
  else
    echo "Proof dir is empty !!!"
  fi
}

function GenerateAfdsmgrConfigs() {

  if [ -f $ALICE_PROOF_AAF_DIR/scripts/afdsmgrd-aaf-integration ];then
    $ALICE_PROOF_AAF_DIR/scripts/afdsmgrd-aaf-integration -b
  else
    echo ""
    echo "Error : script $ALICE_PROOF_AAF_DIR/scripts/afdsmgrd-aaf-integration was not found"
    echo ""
    echo "   please do : ./aaf-installer --sync-alien-packages"
  fi
}

function ClearTmpDirectory() {
  rm -Rf /tmp/ALICE
  rm -Rf /tmp/.alien
  rm -Rf /tmp/xrd-installer-$ALICE_PROOF_AAF_USER
  rm -Rf $ALICE_PROOF_AAF_TMP_DIR
  mkdir -p $ALICE_PROOF_AAF_TMP_DIR/alien/ALICE
  mkdir -p $ALICE_PROOF_AAF_TMP_DIR/.alien
  mkdir -p $ALICE_PROOF_AAF_TMP_DIR/xrd/
  mkdir -p $ALICE_PROOF_AAF_TMP_DIR/home/$ALICE_PROOF_AAF_USER/.alien

  # handle .alien dir
  if [ -d /home/$ALICE_PROOF_AAF_USER/.alien ]; then
    rm -Rf $ALICE_PROOF_AAF_TMP_DIR/.alien
    mv /home/$ALICE_PROOF_AAF_USER/.alien $ALICE_PROOF_AAF_TMP_DIR/
    ln -s $ALICE_PROOF_AAF_TMP_DIR/home/$ALICE_PROOF_AAF_USER/.alien $HOME/.alien
  fi

  ln -s $ALICE_PROOF_AAF_TMP_DIR/alien/ALICE /tmp/ALICE
  ln -s $ALICE_PROOF_AAF_TMP_DIR/.alien /tmp/.alien
  ln -s $ALICE_PROOF_AAF_TMP_DIR/xrd/ /tmp/xrd-installer-$ALICE_PROOF_AAF_USER

  chown -R $ALICE_PROOF_AAF_USER:$ALICE_PROOF_AAF_GROUP $ALICE_PROOF_AAF_TMP_DIR
}

function RestorePROOFNode() {

  RestoreOneFile $ALICE_PROOF_AAF_DIR/backup/proc/sys/fs/file-max /proc/sys/fs/file-max
  RestoreOneFile $ALICE_PROOF_AAF_DIR/backup/etc/sysctl.conf /etc/sysctl.conf
  RestoreOneFile $ALICE_PROOF_AAF_DIR/backup/etc/security/limits.conf /etc/security/limits.conf
  if [ -d $ALICE_PROOF_AAF_DIR/backup ]; then
    rm -Rf $ALICE_PROOF_AAF_DIR/backup
#     echo "You have to logout and login !!!!!!!"
  fi
}

function ChangeDefaultRootVersion() {

  if [ "${AF_ALIROOT_DIR_TEMPLATE:0:6}" = "/cvmfs" ]; then
      
      MY_ROOT_DIR=$(dirname $AF_ALIROOT_DIR_TEMPLATE)
      MY_ROOT_DIR=$(dirname $MY_ROOT_DIR)
      MY_ROOT_DIR="$MY_ROOT_DIR/ROOT"
      if [ -z "$1" ];then
	  echo "List of available versions:"
	  for v in `ls -1 $MY_ROOT_DIR`;do
	      echo "  VO_ALICE@ROOT::$v"
	  done
	  exit 0
      fi
      
      echo "Chaning root to $1 ..."
      
      export PO="`echo $1 | awk -F ':' '{print $1}' | awk -F '@' '{print $1}'`"
      export PN="`echo $1 | awk -F ':' '{print $1}' | awk -F '@' '{print $2}'`"
      export PV="`echo $1 | awk -F ':' '{print $3}'`"
      
      echo "Root is at $MY_ROOT_DIR/$PV ." 
      
      if [ -d "$MY_ROOT_DIR/$PV"  ];then
	  echo ""
	  echo "Doing link 'ln -sfn $MY_ROOT_DIR/$PV $ALICE_PROOF_AAF_DIR/root'"
	  ln -sfn $MY_ROOT_DIR/$PV $ALICE_PROOF_AAF_DIR/root
	  echo "Now you need to restart proof cluster as superuser 'root' :"
	  echo "    $ALICE_PROOF_AAF_DIR/scripts/aaf.sh restart proof"
	  echo ""
      else
	  echo ""
	  echo "Error : ROOT version was not found or wrong format of package !!!"
	  echo ""
      fi

  else
      
      if [ -z "$1" ];then
	  echo "List of available versions:"
	  for v in `ls -1 $ALICE_PROOF_AAF_ALIEN_PACKAGES/VO_ALICE/ROOT/`;do
	      echo "  VO_ALICE@ROOT::$v"
	  done
	  exit 0
      fi
      
      echo "Chaning root to $1 ..."
      
      export PO="`echo $1 | awk -F ':' '{print $1}' | awk -F '@' '{print $1}'`"
      export PN="`echo $1 | awk -F ':' '{print $1}' | awk -F '@' '{print $2}'`"
      export PV="`echo $1 | awk -F ':' '{print $3}'`"
      
      echo "Root is at $ALICE_PROOF_AAF_ALIEN_PACKAGES/$PO/$PN/$PV/$PV ." 
      
      if [ -d $ALICE_PROOF_AAF_ALIEN_PACKAGES/$PO/$PN/$PV/$PV ];then
	  echo ""
	  echo "Doing link 'ln -sfn $ALICE_PROOF_AAF_ALIEN_PACKAGES/$PO/$PN/$PV/$PV $ALICE_PROOF_AAF_DIR/root'"
	  ln -sfn $ALICE_PROOF_AAF_ALIEN_PACKAGES/$PO/$PN/$PV/$PV $ALICE_PROOF_AAF_DIR/root
	  echo "Now you need to restart proof cluster as superuser 'root' :"
	  echo "    $ALICE_PROOF_AAF_DIR/scripts/aaf.sh restart proof"
	  echo ""
      else
	  echo ""
	  echo "Error : ROOT version was not found or wrong format of package !!!"
	  echo ""
      fi
  fi
}

function RefreshProofConfigs() {
  MY_VER=`ls -t1 $ALICE_PROOF_AAF_ALIEN_PACKAGES/VO_ALICE/aaf-proof/ | tail -n 1`
  
  $ALICE_PROOF_AAF_ALIEN_PACKAGES/VO_ALICE/aaf-proof/$MY_VER/scripts/xproofd.sh
  echo "Proof configs updated OK ."
}

function RestoreOneFile() {

  if [ -e $1 ]; then
    echo "Restoring file $2 from $1 ..."
    cp -f $1 $2
  fi
}

function BackupOneFile() {

  if [ ! -e $2 ]; then
    echo "Backuping file $1 to $2 ..."
    cp -f $1 $2
  fi
}

function PrintAafInfoDirecotry() {
  printf "%s=%s [ %s ]\n" "\$$1" "$2" `AAFInfoReturn $2`
}

function AAFInfoReturn() {
  if [ -d $1 ]; then
    printf "OK"
  else
    printf "FAILED"
  fi
}

function PrintAafInfo() {

  if [ ! -e aaf.cf ];then
    echo ""
    echo "AAF config file 'aaf.cf' was NOT found ..."
  fi
  echo ""
#   PrintAafInfoDirecotry ALICE_PROOF_AAF_DIR $ALICE_PROOF_AAF_DIR
#   PrintAafInfoDirecotry ALICE_PROOF_AAF_SHARED_DIR $ALICE_PROOF_AAF_SHARED_DIR
#   PrintAafInfoDirecotry ALICE_PROOF_AAF_ALIEN_API_DIR $ALICE_PROOF_AAF_ALIEN_API_DIR
#   PrintAafInfoDirecotry ALICE_PROOF_AAF_ALIEN_DIR $ALICE_PROOF_AAF_ALIEN_DIR
#   PrintAafInfoDirecotry ALICE_PROOF_AAF_PROOF_DIR $ALICE_PROOF_AAF_PROOF_DIR
#   PrintAafInfoDirecotry ALICE_PROOF_AAF_PROOF_XPROOFD_DIR $ALICE_PROOF_AAF_PROOF_XPROOFD_DIR
  PrintAafInfoDirecotry ALICE_PROOF_AAF_CERTGLOBUS_DIR $ALICE_PROOF_AAF_CERTGLOBUS_DIR

#   PrintAafInfoDirecotry ALICE_PROOF_AAF_ALIEN_SHARED_DIR $ALICE_PROOF_AAF_ALIEN_SHARED_DIR
#   PrintAafInfoDirecotry ALICE_PROOF_AAF_PROOF_ROOT_SHARED_DIR $ALICE_PROOF_AAF_PROOF_ROOT_SHARED_DIR
#   PrintAafInfoDirecotry ALICE_PROOF_AAF_PROOF_XPROOFD_SHARED_DIR $ALICE_PROOF_AAF_PROOF_XPROOFD_SHARED_DIR
  echo ""
}

function ShowHelp() {
  echo "./aaf-installer <options>"
  echo "  --help                       : shows help"
  echo "  --info                       : shows AAF info"
  echo "  --clean-all-as-root          : clean AAF node"
  echo "  --pre-install-as-root        : does preinstallation of AAF"
  echo "  --install-master             : install AAF master"
  echo "  --install-worker             : install AAF worker"
  echo "  --sync-alien-packages        : sync alien packages"
  echo "  --upgrade-aaf                : Upgrade AAF"
  echo "  --apply-aaf-config           : Apply new aaf.cf"
	echo ""
  echo "  --update-proof-packages      : Update proof pacakges (run on master only)"
  echo "  --check-packages-install     : Checks that the alien packages are installed correctly (run on master only)"
  echo "  --rebuild-proof-packages     : Rebuild proof pacakges (run on master only)"
  echo "  --create-aliroot-depfile     : Creates text file with aliroot dependencies (run on master only)"
  echo ""
  echo "  --generate-afdsmgrd-config   : generates new afdsmgrd config (run on master only as AAF user)"
  echo "  --update-afdsmgrd-links      : updates afdsmgrd links (run on master only as root user)"
  echo "  --set-default-root-for-proof : sets default root to be used for proof"
  
  echo "extra:"
  echo "  --upgrade-alien              : re-install alien"
  echo "  --install-alien-shared       : install shared alien"
  echo ""

#   echo "  --restore                   : restore worker"
#   echo "  --install-alien             : install alien on worker"
#   echo "  --install-xrootd            : install alien on worker"
#   echo "  --setup-xrootd-redirector   : install xrootd on worker"
#   echo "  --setup-xrootd-server       : install xrootd on worker"
#   echo "  --setup-proof               : setup proof settings"


#   PrintAafInfo

}

function RunCMDAsUser() {
  TMPUSER=$1
  shift

  if [ "`whoami`" == "root" ];then
    su - $TMPUSER -c "$*"
  else
    cmd=`$*`
    echo "\$cmd = $cmd"
  fi
}

function CreateDepFile() { 

  if [ -z "$3" ];then
    AliEnCreateProxy
  fi
  f="$2/$1_deps.txt"
  tmpf="/tmp/$1_deps.txt"
  mkdir -p $2
  if [ "$?" != "0" ]; then
    echo "Unable to create directory $2. Aborting."
    return 1
  fi
  echo -n "" > $f

  case $1 in
    aliroot)
      echo "Creating dependency file $f (it may take while) ..."
#      for aliroot in `$ALICE_PROOF_AAF_DIR/alien/bin/alien -user proof -exec packman list $AAF_PACKMAN_SOURCE 2>& 1| grep "VO_ALICE@AliRoot"`; do
#        deps=`$ALICE_PROOF_AAF_DIR/alien/bin/alien -user proof -exec packman $AAF_PACKMAN_SOURCE dependencies $aliroot 2>& 1| grep "dependencies:" | awk '{print $2}'`
#        echo "$aliroot|${deps%,*}|${deps#*,}" >> $f 
#      done
        deps=`wget -q -O - http://pcalienbuild4.cern.ch:8889/tarballs/Packages | grep -i "VO_ALICE@AliRoot" | sed -e "s/\s\+/ /g" | awk '{printf "%s %s\n", $5, $6}' | tr " " "|" | tr "," "|"`
        echo "$deps" > $tmpf
	sort -u $tmpf > /dev/null 2>&1
       for av in `ls $ALICE_PROOF_AAF_ALIEN_PACKAGES/VO_ALICE/AliRoot`; do
         grep "AliRoot::$av" $tmpf >> $f
       done
      rm -f $tmpf

      if [ -e $f ]; then
	echo "Dependency file $f was created ..."
      else
	echo "Dependency file $f was NOT created ..."
	return 1
      fi
    ;;
    *)
      echo "Cannot create depfile for $1. Unknown parameter."
      return 1
    ;;
  esac
  if [ -z "$3" ];then
    AliEnDestroyProxy
  fi
}

checkAAFInstallerVersion $0

if [ "$#" == "0" ]; then
  SetVariables
  ShowHelp
  exit 1
fi

  sed -i -e "s/proof@aaf-xrootd/VO_ALICE@aaf-xrootd/g" ${AAF_CF_DIR}aaf.cf
  sed -i -e "s/proof@aaf-aliroot/VO_ALICE@aaf-aliroot/g" ${AAF_CF_DIR}aaf.cf
  sed -i -e "s/proof@aaf-proof/VO_ALICE@aaf-proof/g" ${AAF_CF_DIR}aaf.cf

while [[ $1 = -* ]]; do
    arg=$1; shift           # shift the found arg away.

    case $arg in
#         --foo)
#             do_foo "$2"
#             shift
#             ;;
        --help)
            ShowHelp
            ;;
        --info)
	    SetVariables
            PrintAafInfo
            ;;
        --clean-all-as-root)
	    CheckRoot
	    SetVariables
	    RestorePROOFNode
            CleanAAF
            ;;
        --restore)
	    SetVariables
            RestorePROOFNode
            ;;
	--pre-install-as-root)
	    SetVariables
	    InstallAAF
            InitXrootdVMSS
            ;;
        --install-master)
	    SetVariables
	    CheckUser
            InstallAAFAsUser
            SetupXrootdVMSSRedirector
	    if [ "$?" != "0" ];then
	      echo "Error in SetupXrootdVMSSRedirector !!!"
	      exit 1
	    fi
	    SetupPROOF
	    AliEnPackagesSync
	    if [ "$?" != "0" ];then
	      echo "Error in AliEnPackagesSync !!!"
	      exit 2
	    fi
	    UpgradeAAF
            ;;
        --install-worker)
	    SetVariables
	    CheckUser
            InstallAAFAsUser
            SetupXrootdVMSSServer
	    if [ "$?" != "0" ];then
	      echo "Error in SetupXrootdVMSSServer !!!"
	      exit 1
	    fi
	    SetupPROOF
	    AliEnPackagesSync
	    if [ "$?" != "0" ];then
	      echo "Error in AliEnPackagesSync !!!"
	      exit 2
	    fi
	    UpgradeAAF
            ;;
        --install-master-and-worker)
	    SetVariables
	    CheckUser
            InstallAAFAsUser
            SetupXrootdVMSSRedirector 2in1
	    if [ "$?" != "0" ];then
	      echo "Error in SetupXrootdVMSSServer !!!"
	      exit 1
	    fi
	    SetupPROOF
	    AliEnPackagesSync
	    if [ "$?" != "0" ];then
	      echo "Error in AliEnPackagesSync !!!"
	      exit 2
	    fi
	    UpgradeAAF
            ;;
        --sync-alien-packages)
	    SetVariables
	    CheckUser
            AliEnPackagesSync
	    if [ "$?" != "0" ];then
	      echo "Error in AliEnPackagesSync !!!"
	      exit 7
	    fi
            ;;
      --sync-alien-packages-cron)
	    SetVariables
	    CheckUser
      AliEnPackagesSync
	    if [ "$?" != "0" ];then
	      echo "Error in AliEnPackagesSync !!!"
	      exit 7
	    fi
	    UpdateProofPackages 10 300
	    if [ "$?" != "0" ];then
	      echo "Error in UpdateProofPackages !!!"
	      exit 7
	    fi
            ;;
        --upgrade-aaf)
	    SetVariables
	    CheckUser
	    UpgradeAAF
            ;;
        --install-alien)
	    SetVariables
	    CheckUser
            InstallAliEn
	    if [ "$?" != "0" ];then
	      echo "Error in InstallAliEn !!!"
	      exit 1
	    fi
            ;;
        --upgrade-alien)
	    SetVariables
	    CheckUser
            InstallAliEn
	    if [ "$?" != "0" ];then
	      echo "Error in InstallAliEn !!!"
	      exit 1
	    fi
            ;;

        --install-alien-shared)
	    SetVariables
	    CheckUser
            InstallAliEn
	    if [ "$?" != "0" ];then
	      echo "Error in ReInstallAliEn !!!"
	      exit 1
	    fi
            ;;
        --upgrade-alien)
	    SetVariables
	    CheckUser
            InstallAliEn "REINSTALL"
	    if [ "$?" != "0" ];then
	      echo "Error in InstallAliEn !!!"
	      exit 1
	    fi
            ;;
	--rebuild-proof-packages)
	    SetVariables
	    CheckUser
	    UpdateProofPackages 5 5 REBUILD
	    if [ "$?" != "0" ];then
	      echo "Error in UpdateProofPackages !!!"
	      exit 7
	    fi
            ;;
	--update-proof-packages)
	    SetVariables
	    CheckUser
	    UpdateProofPackages 5 5
	    if [ "$?" != "0" ];then
	      echo "Error in UpdateProofPackages !!!"
	      exit 7
	    fi
            ;;

	--check-packages-install)
	   SetVariables
	   CheckUser
	   package_dirs="$ALICE_PROOF_AAF_ALIEN_PACKAGES/VO_ALICE $ALICE_PROOF_AAF_ALIEN_PACKAGES/proof"
	   CheckPackagesInstallation "" "$package_dirs" "1" "4"
	   if [ "$?" != "0" ]; then
	     echo "Error in CheckPackagesInstallation !!!"
	     exit 9
	   fi
	   ;;
	--create-aliroot-depfile)
	    SetVariables
	    CheckUser
	    CreateDepFile "aliroot" "$ALICE_PROOF_AAF_ALIEN_PACKAGES/deps"
	    if [ "$?" != "0" ]; then
	      echo "Error creating aliroot dependencies file. Aborting."
	      exit 8
	    fi
	    ;;

	--apply-aaf-config)
	    SetVariables
	    CheckUser
	    UpdateSettingWithAAFConfig
	    if [ "$?" != "0" ]; then
	      echo "Error UpdateSettingWithAAFConfig. Aborting."
	      exit 8
	    fi
	    ;;
  --generate-afdsmgrd-config)
      SetVariables
      CheckUser
      GenerateAfdsmgrConfigs
      ;;
   --update-afdsmgrd-links)
      SetVariables
      CheckRoot
      RecreateAfdsmgrLinks
      ;;
      
    --set-default-root-for-proof)
      SetVariables
      CheckUser
      ChangeDefaultRootVersion $1
      ;;
      
    --refresh-proof-configs)
      SetVariables
      CheckUser
      RefreshProofConfigs
      ;;
      
      

# 	--setup-proof)
# 	    SetVariables
# 	    CheckUser
#             SetupPROOF
# 	    if [ "$?" != "0" ];then
# 	      echo "Error in SetupPROOF !!!"
# 	      exit 7
# 	    fi
#             ;;
	*)
	    ShowHelp
	    exit 1 
	    ;;
    esac
done
